<template>
  <view>
    <mxp-popup ref="mxpPopupRef" :height="`${popupHeight}px`" :toolbarOptions="{ showConfirm: false, title: '请选择兑换短剧', height: '60px' }">
      <view style="box-sizing: border-box; width: 100vw; height: 55px; padding: 0 30rpx">
        <mxp-search v-model="search" background="#eeeeee" @confirm="onSearch"></mxp-search>
      </view>
      <mxp-refresh-scroll-view
        ref="mxpRefreshScrollViewRef"
        :height="`${popupHeight - 55}px`"
        :style="{ height: `${popupHeight - 55}px`, width: '750rpx' }"
        :queryData="getDramaListList"
      >
        <view v-for="(item, index) in dramaList" :key="index" class="view-record" :class="{ 'view-record-not-first': index !== 0 }">
          <view class="img-box">
            <mxp-image width="160rpx" height="260rpx" errorSize="22px" borderRadius="10px" :src="item.dramaCover"></mxp-image>
          </view>
          <view style="display: flex; flex: 1; flex-direction: column; justify-content: center; width: 100%; padding: 0 14px">
            <view class="record-title-box">
              <text class="record-title">
                <text v-for="(i, idx) in item.dramaTitle" :key="`${i}-${idx}`" :style="{ color: !~search.indexOf(i) ? '' : 'red' }">{{ i }}</text>
              </text>
            </view>
            <view class="record-info-box">
              <text class="record-info">观看至{{ item.episodeSeq }}集</text>
              <text class="record-info">共{{ item.seqNum }}集</text>
            </view>
            <view class="record-info-box">
              <text class="intro record-info">简介: {{ item.dramaDesp || '' }}</text>
            </view>
            <view class="butt-box" @click="useDiscountCoupon(item)">
              <text style="font-size: 12px; color: #ffffff">立即兑换</text>
            </view>
          </view>
        </view>
      </mxp-refresh-scroll-view>
    </mxp-popup>
  </view>
</template>

<script setup lang="ts">
  import { computed, nextTick, ref } from 'vue';
  import MxpPopup from '@/mxp-ui/mxp-popup/mxp-popup.vue';
  import MxpSearch from '@/mxp-ui/mxp-search/mxp-search.vue';
  import { type Coupon, useDiscountCouponAxios } from '@/api/rest';
  import MxpImage from '@/mxp-ui/mxp-image/mxp-image.vue';
  import MxpRefreshScrollView, { type Ins } from '@/mxp-ui/mxp-refresh-scroll-view/mxp-refresh-scroll-view.vue';
  import { type SearchDrama, searchDramaListAxios } from '@/api/drama';
  import useMxpToastRefHooks from '@/utils/hooks/useToast';
  import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';

  const mxpToastRef = useMxpToastRefHooks();
  export type ShowEvent = {
    /** 优惠券信息 */
    coupon: Coupon;
    /** 兑换成功 */
    success?: () => void;
  };
  const sys = mxpGetSysInfoStore().getSysInfo();

  const popupHeight = computed(() => Math.floor(sys.value.windowHeight * 0.8));

  let success: ShowEvent['success'] | undefined = undefined;
  const search = ref('');
  const dramaList = ref<SearchDrama[]>([]);
  const coupon = ref<Coupon | undefined>();
  const mxpRefreshScrollViewRef = ref<InstanceType<typeof MxpRefreshScrollView>>();
  const mxpPopupRef = ref<InstanceType<typeof MxpPopup> | null>(null);
  /** 显示 */
  function show(data: ShowEvent) {
    coupon.value = data.coupon;
    success = data.success;

    mxpPopupRef.value?.show();
  }

  /** 隐藏 */
  function hide() {
    mxpPopupRef.value?.hide();
  }

  /** 搜索 */
  function onSearch() {
    nextTick(() => {
      dramaList.value = [];
      mxpRefreshScrollViewRef.value?.initLoadRefresh();
    });
  }

  /** 搜索发现列表 */
  async function getDramaListList(ins: Ins) {
    try {
      const res = await searchDramaListAxios(ins.page, ins.size, search.value);
      dramaList.value = ins.page > 1 ? dramaList.value.concat(res.data.records) : res.data.records;
      ins.setMoreSuccess(res.data.records.length, res.data.total);
    } catch (error) {
      ins.setMoreEmpty('fail_load', error.msg || '获取数据失败，BD001');
    }
  }

  /**
   * 使用优惠券
   */
  async function useDiscountCoupon(drama: SearchDrama) {
    try {
      await useDiscountCouponAxios(coupon.value!.userCouponId, drama.dramaId!);
      mxpToastRef.value?.showSuccess('已兑换');
      typeof success === 'function' && success();
      hide();
    } catch (error) {
      mxpToastRef.value?.showError(error.msg || '兑换失败');
      console.log('error====', error);
    }
  }

  defineExpose({
    /** 显示 */
    show,
    /** 隐藏 */
    hide,
  });
</script>

<style lang="scss" scoped>
  .view-record-not-first {
    padding-top: 8px;
    border-top: 1px solid #eee9e9;
  }

  .view-record {
    position: relative;
    display: flex;
    width: 690rpx;
    margin-bottom: 8px;
    margin-left: 30rpx;
    vertical-align: top;
    border-radius: 10px;

    .record-title-box {
      width: 100%;

      .record-title {
        overflow: hidden;
        font-size: 16px;
        font-weight: bold;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .record-info-box {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      width: 100%;
      margin-top: 6px;

      .record-info {
        font-size: 12px;
        text-align: justify;
      }

      .intro {
        display: -webkit-box;
        overflow: hidden;
        word-break: break-all;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
      }
    }

    .butt-box {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 70px;
      padding: 6px;
      margin-top: 16px;
      background: linear-gradient(to right, #fdbe00 0%, #f66f00 100%);
      border-radius: 20px;
    }
  }
</style>
